import express  from 'express';
import { checkSchema, validationResult } from 'express-validator'  
import util from 'utility'
import jwt from 'jsonwebtoken';  

const router = express.Router();  
function generateToken(user) {  
    const secretKey = 'qfdixon'; // 替换为你的密钥  
    return jwt.sign({ user }, secretKey, { expiresIn: '24h' });  
  }  

// 登录注册一体的api
router.post('/login', checkSchema({
    code:{ notEmpty: true,errorMessage:'密码不能为空' },
    phone: { notEmpty: true, errorMessage:'手机号码不能为空' }
}), async (req,res)=>{
    res.validator();
    const { code, phone } = req.body;

    // 先验证code 
    const saveCode = req.nodeCache.get(`code_login_${phone}`);
    
    if(saveCode !== code) {
        res.fail('验证码不匹配')
        return 
    }

    // 先判断用户是否存在
    const user = await req.prisma.User.findFirst({
        where:{
            phone
        }
    })

    if(user){
        // 登录流程
        
        const token = generateToken({ phone, uid: user.id })
        res.success({token,phone})

    } else {
        // 注册流程
        const { pwd ,phone,type='custom'  } = req.body;
        // const _pwd = util.md5(pwd);
      
        const newUser = await req.prisma.User.create({
            data:{
                // pwd: _pwd,
                phone,
                type: type
            }
        })

        const token = generateToken({ phone, uid: newUser.id })
        res.success({token,phone})

    }
  
})

router.post('/status',(req,res)=>{
    const secretKey = 'qfdixon'; // 替换为你的密钥  
    const token = req.headers['authorization'];  
    console.log('token', token);
    if (!token) return res.sendStatus(401);  
    jwt.verify(token, secretKey, {
      maxAge: '1d'
    }, (err, user) => {  
        if(err){
            return res.fail();
        }
        res.success()
    });  
})

export default router

